<?php

namespace Helper\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;
use Biz\JPusher;
use Carbon\Carbon;

class NotificationModel extends BaseModel
{
    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
    ];

    protected $_validate = [
    ];

    /**
     * 回答问题
     *
     * @param array $srcUser 回答者
     * @param array $question 问题
     * @return void
     */
    public function answerQuestion($srcUser, $question, $answer)
    {
        $body = $question['body'];
        $body = mb_strlen($body) > 10 ? mb_substr($body, 0, 10) . '...' : $body;
        $msg = "{$srcUser['nickname']}回答了你的问题[{$body}]";
        $extra = [
            'action' => 'openAnswer',
            'data' => [
                'answer_id' => $answer['id'],
            ],
        ];
        return $this->notify($question['user_id'], $msg, 1, 'qa', $extra);
    }    

    /**
     * 采纳答案
     *
     * @param [type] $author
     * @param [type] $question
     * @param [type] $answer
     * @return void
     */
    public function adoptAnswer($author, $question, $answer)
    {
        $msg = "{$author['nickname']}在[{$question['title']}]问题中采纳了你的答案";
        $extra = [
            'action' => 'openAnswer',
            'data' => [
                'answer_id' => $answer['id'],
            ],
        ];
        return $this->notify($answer['user_id'], $msg, 1, 'qa', $extra);
    }

    /**
     * 私聊
     *
     * @return boolean
     */
    public function privateChat($from, $to, $msg)
    {
        $msg = "[{$from['nickname']}]私聊了你:{$msg}";
        $extra = [
            'action' => 'privateChat',
            'data' => [
                'im_account' => $from['user_id'],
            ],
        ];
        return $this->notify($to['user_id'], $msg, 1, 'user', $extra);
    }

    /**
     * 邀请回答
     *
     * @return void
     */
    public function inviteAnswers($inviteeIds, $inviter, $question)
    {
        $msg = "{$inviter['nickname']}邀请您回答[{$question['title']}]";
        $extra = [
            'action' => 'inviteAnswer',
            'data' => [
                'question_id' => $question['id'],
            ],
        ];
        // $invitees = is_array($invitees) ? array_column($invitees, 'user_id') : $invitees['user_id'];
        return $this->notify($inviteeIds, $msg, 1, 'qa', $extra);
    }

    /**
     * 打赏 
     */
    public function reward($fromUser, $toUser, $amount)
    {
        $msg = "[{$fromUser['nickname']}]打赏了你" . round($amount/100, 2) . '元';
        return $this->notify($toUser['user_id'], $msg, 1, 'user');
    }


    /**
     * 关注 
     */
    public function following($from, $to)
    {
        $msg = "[{$from['nickname']}]关注了你";
        return $this->notify($to['user_id'], $msg, 1, 'user');
    }

    /**
     * 回复
     */
    public function reply($from, $to, $isPost = false)
    {
        // 回复你的帖子 -> 评论
        // 回复你的评论 -> 回复
        $txt = $isPost ? '评论' : '回复';
        $msg = "[{$from['nickname']}]在帖子中{$txt}了你";
        return $this->notify($to['user_id'], $msg, 1, 'user');
    }

    /**
     * 点赞
     * @return void
     */
    public function parise($from, $to)
    {
        $msg = "[{$from['nickname']}]赞了你";
        return $this->notify($to['user_id'], $msg, 1, 'user');
    }

    public function notify($userId, $body, $priority = 1, $group, $extra = null)
    {
        // 加入系统消息
        if (is_array($userId)) {
            foreach ($userId as $uid) {
                $data = [
                    'user_id' => $uid,
                    'body' => $body,
                    'priority' => $priority,
                    'created_at' => time(),
                    'extra' => $extra ? serialize($extra) : '',
                    'group' => $group,
                ];
                D('Notification')->add($data);
            }
        } else {
            $data = [
                'user_id' => $userId,
                'body' => $body,
                'priority' => $priority,
                'created_at' => time(),
                'extra' => $extra ? serialize($extra) : '',
                'group' => $group,
            ];
            D('Notification')->add($data);
        }

        //推送
        $jpusher = new JPusher();
        try {
            $ret = $jpusher->push($body, $userId, $extra);
            // dump($ret);
            return true;
        } catch (\Exception $e) {
            // dump($e);
        }
    }


    protected function _after_find(&$record, $options)
    {
        Carbon::setLocale('zh');
        $record['extra'] = $record['extra'] !== '' ? unserialize($record['extra']) : null;
        $record['human_time'] = Carbon::createFromTimestamp($record['created_at'])->diffForHumans();
    }

    protected function _after_select(&$records, $options)
    {
        Carbon::setLocale('zh');
        foreach ($records as &$record) {
            $record['extra'] = $record['extra'] !== '' ? unserialize($record['extra']) : null;
            $record['human_time'] = Carbon::createFromTimestamp($record['created_at'])->diffForHumans();
        }
    }


}
